<?php 
	class Users extends CI_Model{

	 	function __construct(){
        	parent::__construct();
    	}
		/**
		* 函数功能介绍：获取直播历史
		* 创建人: 	Zhang Shaowei
		* 创建时间: 2015-09-09 11:35
		* 最后修改人：
		* 最后修改时间：
		*/
		function get_anchor_log($conditon = array()) {
			$where=' ';
			if(isset($conditon['cdn'])){
				$where = ' AND cdn='.$conditon['cdn'];
			}
			$sql = "SELECT * FROM {$this->db->dbprefix}user_anchor_log WHERE is_video = 1".$where;
			$result = $this->db->query($sql)->result_array();
			return $result;
		}
		
		function get_field_by_where($fields, $where = "1=1"){
			$sql = "SELECT $fields FROM {$this->db->dbprefix}user WHERE $where";
			$result = $this->db->query($sql)->row_array();
			return $result;
		}
    	/**
		* 函数功能介绍：查询用户送出的卷的排行(仅用于生成redis缓存)
		* 创建人: 	Zhou Hailong
		* 创建时间: 2016-01-27 14:01
		* 最后修改人：
		* 最后修改时间：
		*/
    	function send_coupon_max($type = ''){
    		$where = "WHERE u.status > 0";
    		if($type == 'day'){
				$start_time = strtotime(date("Y-m-d", time()));
				$end_time = $start_time + 24 * 3600;
			}

			if($type == 'week'){
				$start_time = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y"));
				$end_time = $start_time + 24 * 3600 * 7;
			}

			if($type == 'month'){
				$start_time = mktime(0, 0, 0, date("m") -1 , 1, date("Y"));
				$end_time = mktime(0, 0, 0, date("m"), 1, date("Y"));
			}

			if($type != '' && $type != 'all'){
				$where .= " AND gr.add_time >= $start_time AND gr.add_time < $end_time";	
			}

 			$fileds = "SUM(gr.coin) AS coupon, ut.type_name, u.type_id, a.name, a.logo, u.id AS uid, u.aid, u.nick, u.head_image_url, u.sex, u.verified_anchor, u.signature, u.is_live, u.is_push, u.f_count, u.v_count";
			$sql  = "SELECT $fileds FROM {$this->db->dbprefix}gift_give_record AS gr ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user AS u ON(gr.uid=u.id) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}alliance AS a ON(a.id = u.aid) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user_type AS ut ON(ut.id = u.type_id) ";
			$sql .= "$where GROUP BY gr.uid ORDER BY coupon DESC LIMIT 20";
			$result = $this->db->query($sql)->result_array();
			return $result;
    	}

    	/**
		* 函数功能介绍：查询主播收到的卷的排行(仅用于生成redis缓存)
		* 创建人: 	Zhou Hailong
		* 创建时间: 2016-01-27 14:42
		* 最后修改人：
		* 最后修改时间：
		*/
    	function get_coupon_max($type = ''){
    		$where = "WHERE u.status = 1 ";//AND u.verified_anchor = 1
    		if($type == 'day'){
				$start_time = strtotime(date("Y-m-d", time()));
				$end_time = $start_time + 24 * 3600;
			}

			if($type == 'week'){
				$start_time = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y"));
				$end_time = $start_time + 24 * 3600 * 7;
			}

			if($type == 'month'){
				$start_time = mktime(0, 0, 0, date("m") -1 , 1, date("Y"));
				$end_time = mktime(0, 0, 0, date("m"), 1, date("Y"));
			}

			if($type != '' && $type != 'all'){
				$where .= " AND gr.add_time >= $start_time AND gr.add_time < $end_time";	
			}

 			$fileds = "SUM(gr.currency) AS coupon, ut.type_name, u.type_id, a.name, a.logo, u.id AS uid, u.aid, u.nick, u.head_image_url, u.sex, u.verified_anchor, u.signature, u.is_live, u.is_push, u.f_count, u.v_count";
			$sql  = "SELECT $fileds FROM {$this->db->dbprefix}gift_give_record AS gr ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user AS u ON(gr.anchor_id=u.id) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}alliance AS a ON(a.id = u.aid) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user_type AS ut ON(ut.id = u.type_id) ";
			$sql .= "$where GROUP BY gr.anchor_id ORDER BY coupon DESC LIMIT 20";
			$result = $this->db->query($sql)->result_array();
			return $result;
    	}

    	/**
		* 函数功能介绍：查询主播收到的币的排行(仅用于生成redis缓存)
		* 创建人: 	Zhou Hailong
		* 创建时间: 2016-01-27 15:21
		* 最后修改人：
		* 最后修改时间：
		*/
    	function get_coin_max($type = ''){
    		$where = "WHERE u.status = 1 ";//AND u.verified_anchor = 1
    		if($type == 'day'){
				$start_time = strtotime(date("Y-m-d", time()));
				$end_time = $start_time + 24 * 3600;
			}

			if($type == 'week'){
				$start_time = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y"));
				$end_time = $start_time + 24 * 3600 * 7;
			}

			if($type == 'month'){
				$start_time = mktime(0, 0, 0, date("m") -1 , 1, date("Y"));
				$end_time = mktime(0, 0, 0, date("m"), 1, date("Y"));
			}

			if($type != '' && $type != 'all'){
				$where .= " AND gr.add_time >= $start_time AND gr.add_time < $end_time";	
			}

 			$fileds = "SUM(gr.currency) AS coin, ut.type_name, u.type_id, a.name, a.logo, u.id AS uid, u.aid, u.nick, u.head_image_url, u.sex, u.verified_anchor, u.signature, u.is_live, u.is_push, u.f_count, u.v_count";
			$sql  = "SELECT $fileds FROM {$this->db->dbprefix}gift_give_record AS gr ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user AS u ON(gr.anchor_id=u.id) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}alliance AS a ON(a.id = u.aid) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user_type AS ut ON(ut.id = u.type_id) ";
			$sql .= "$where GROUP BY gr.anchor_id ORDER BY coin DESC LIMIT 20";
			$result = $this->db->query($sql)->result_array();
			return $result;
    	}

    	/**
		* 函数功能介绍：查询用户送出的币的排行(仅用于生成redis缓存)
		* 创建人: 	Zhou Hailong
		* 创建时间: 2016-01-27 15:36
		* 最后修改人：
		* 最后修改时间：
		*/
    	function send_coin_max($type = ''){
    		$where = "WHERE u.status = 1";
    		if($type == 'day'){
				$start_time = strtotime(date("Y-m-d", time()));
				$end_time = $start_time + 24 * 3600;
			}

			if($type == 'week'){
				$start_time = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y"));
				$end_time = $start_time + 24 * 3600 * 7;
			}

			if($type == 'month'){
				$start_time = mktime(0, 0, 0, date("m") -1 , 1, date("Y"));
				$end_time = mktime(0, 0, 0, date("m"), 1, date("Y"));
			}

			if($type != '' && $type != 'all'){
				$where .= " AND gr.add_time >= $start_time AND gr.add_time < $end_time";	
			}

 			$fileds = "SUM(gr.coin) AS coin, ut.type_name, u.type_id, a.name, a.logo, u.id AS uid, u.aid, u.nick, u.head_image_url, u.sex, u.verified_anchor, u.signature, u.is_live, u.is_push, u.f_count, u.v_count";
			$sql  = "SELECT $fileds FROM {$this->db->dbprefix}gift_give_record AS gr ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user AS u ON(gr.uid=u.id) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}alliance AS a ON(a.id = u.aid) ";
			$sql .= "LEFT JOIN {$this->db->dbprefix}user_type AS ut ON(ut.id = u.type_id) ";
			$sql .= "$where GROUP BY gr.uid ORDER BY coin DESC LIMIT 20";
			$result = $this->db->query($sql)->result_array();
			return $result;
    	}
		
		/**
		* 函数功能介绍：获取正在直播列表
		* 创建人: 	Zhang Shaowei
		* 创建时间: 2015-07-16 17:35
		* 最后修改人：
		* 最后修改时间：
		*/
		
		function get_live_list($data = array(),$limit = 0, $offset = 10,$order_by = 'u.start_time DESC',$fileds = '') {
			
			$where = " WHERE 1=1 AND u.status = 1 ";
			
			if(!empty($data['is_live'])) {
				$where.=" AND u.is_live = 1";
			}

			if(!empty($data['is_push'])) {
				$where.=" AND u.is_push = 1";
			}
			
			if(!empty($data['not_uid'])) {
				$where.=" AND u.id NOT IN(". $data['not_uid'] .") ";
			}
			if(!empty($data['uid'])) {
				$where.=" AND u.id IN(". $data['uid'] .") ";
			}
			if(!empty($data['in_uid'])) {
				$where.=" AND u.id = ".$data['in_uid'];
			}
			
			if(!empty($data['verified_anchor'])) {
				$where.=" AND u.verified_anchor = " .$data['verified_anchor'];
			}
			if(!empty($data['aid'])) {
				$where.=" AND u.aid = " .$data['aid'];
			}

			if(!empty($data['stream_id'])) {
				$where .=" AND u.stream_id = '".$data['stream_id']  ."'";
			}


			if(empty($fileds)) {
				$fileds = 'u.id AS uid,u.house_password,u.type_id,u.nick, u.signature, u.head_image_url,u.sex,u.image_url,u.realtime_image_url,u.verified_anchor,u.province,u.city, u.is_live, u.is_push, u.static, a.id AS alliance_id,a.name AS alliance_name,a.logo AS alliance_logo,u.title,u.description,u.orientation,u.start_time,u.f_count, u.up_count, u.live_up_count,u.h_count,u.cdn,u.disconnect_time,SUM(ggr.currency) AS gift_coupon, u.h_count_base,u.cate_id ';//,SUM(ggr.coin) AS gift_coin
			}
			$sql = "SELECT ". $fileds ." FROM " . $this->db->dbprefix('user') . " AS u ";
			$sql .= "LEFT JOIN " . $this->db->dbprefix('alliance') . " AS a ON (u.aid = a.id ) ";
			$sql .= "LEFT JOIN " . $this->db->dbprefix('gift_give_record') . " AS ggr ON (ggr.anchor_id = u.id) ";
			$sql .= $where;
			$sql .= " GROUP BY u.id ORDER BY ". $order_by;
			if(intval($offset) > 0){
				$sql .= " LIMIT $limit, $offset";
			}
			$result = $this->db->query($sql)->result_array();
			return $result;
		}
		function return_live_list ($lists = array() ) {
			$this->load->library('redis',array('model'=>'anchor_redis','channel'=>'live'),'anchor_redis');
			$this->load->library('redis',array('model'=>'xmpp_redis','channel'=>'im'),'xmpp_redis');
			foreach($lists as $key=>$val) {
				$lists[$key]['h_count']	= (int) $val['h_count'];
				$lists[$key]['uid']		= (int) $val['uid'];
				$lists[$key]['sex']		= (int) $val['sex'];
				$lists[$key]['verified_anchor']	= (int) $val['verified_anchor'];
				$lists[$key]['orientation']		= (int) $val['orientation'];
				$lists[$key]['start_time']		= (int) $val['start_time'];
				$lists[$key]['history_count'] 	= count($this->xmpp_redis->redis_class->get_room_history_by_members_temp($val['uid']));
				
				if( ($val['is_live'] == 1 && $val['is_push'] == 1 ) || $val['static'] == 1) {
					$lists[$key]['live'] = 1; 
				}else {
					$lists[$key]['live'] = 0; 
				}
				if(!empty($val['cdn'])) {
					try {
						$return_list = $this->anchor_redis->redis_class->get_live_video_url($val['uid'],$val['cdn']);
						
						$lists[$key]['video_url'] 		= !empty($return_list['rtmp_video_url']) ? $return_list['rtmp_video_url'] : '';
						$lists[$key]['hls_video_url'] 	= !empty($return_list['hls_video_url']) ? $return_list['hls_video_url'] : '';
						$lists[$key]['flv_video_url'] 	= !empty($return_list['flv_video_url']) ? $return_list['flv_video_url'] : '';
					}catch (Exception $e) {
						$lists[$key]['video_url'] 		= '';
						$lists[$key]['hls_video_url'] 	= '';
						$lists[$key]['flv_video_url'] 	= '';
					}
				}else {
					$lists[$key]['video_url'] = '';
				}
				unset($lists[$key]['cdn']);
			}
			return $lists;
		}

		//增加用户币数
		function increase_coin($uid, $number){
			$sql = "UPDATE {$this->db->dbprefix}user SET coin = coin + $number WHERE id=$uid";
			$result = $this->db->query($sql);
		}
		
		/**
		* 函数功能介绍：增加用户视频数
		* 创建人: Zhou hailong
		* 创建时间: 2016-01-27 17:31
		* 最后修改人：
		* 最后修改时间：
		*/
		function increase_v_count($uid){
			$sql = "UPDATE {$this->db->dbprefix}user SET v_count = v_count + 1 WHERE id = $uid";
			return $this->db->query($sql);
		}
		
		function get_user_type_name($type_id){
			$type_name='';
			$type_id=intval($type_id);
			
			if($type_id > 0){
				$info = get_field_by_where('user_type', '*', 'id=' . $type_id);
				if(!empty($info)){
					$type_name = $info['type_name'];
				}
			}
			
			return $type_name;
		}
		
		function reduce_user_currency($uid, $currency){
			$sql = "UPDATE {$this->db->dbprefix}user SET coupon = coupon - $currency WHERE id = $uid and (coupon-".$currency." >= 0)";
			$this->db->query($sql);
			if($this->db->affected_rows() > 0){
				return  true;
			}else{
				return  false;
			}
		}
		
		function get_user_level_info($uid){
			$return_arr=array('user_level_sign'=>'','user_level_name'=>'','min_experience'=>'','max_experience'=>'');
			
			$user_info=get_field_by_where("user", "user_level_sign,experience", "id='{$uid}'");
			if(empty($user_info)) return $return_arr;
			//用户等级名字
			if(!empty($user_info['user_level_sign'])){
				$level_info=get_field_by_where("user_level", "name,sign,min_experience,max_experience", "sign='{$user_info['user_level_sign']}'");
			}
			if(empty($level_info)){//没有取到等级则取默认最低的等级名字
				$level_info=get_field_by_where("user_level", "name,sign,min_experience,max_experience", "min_experience<={$user_info['experience']} ORDER BY min_experience DESC");
				if(!empty($level_info)){
					$user_info['user_level_sign']=$level_info['sign'];
					$this->db->update('user', array('user_level_sign' => $level_info['sign']), array('id' => $uid));
				}
			}
			
			$return_arr['user_level_sign']=isset($level_info['sign'])?$level_info['sign']:'';
			$return_arr['user_level_name']=isset($level_info['name'])?$level_info['name']:'';
			$return_arr['min_experience']=isset($level_info['min_experience'])?$level_info['min_experience']:'';
			$return_arr['max_experience']=isset($level_info['max_experience'])?$level_info['max_experience']:'';
			
			return $return_arr;
		}
		
		
		/**
		* 函数功能介绍：获取广告的其他内容
		* 创建人: 	Zhou Hailong
		* 创建时间: 2016-01-15 16:49
		* 最后修改人：
		* 最后修改时间：
		* @param 
		*/
		function return_ad_other_info($ad_data, $mi_uid = 0){
			
			$this->load->model("users");
			
			$ad_list = $ad_data;
			$uids = array();	//用户ID ad_type=2,用于批量获取用户的粉丝数
			$video_ids = array(); //视频ID ad_type=3,用于批量获取视频的播放量
			$video_user_ids = array(); //视频ID ad_type=3,用于批量获取用户信息
			$live_uids = array(); //正在直播的用户ID, ad_type=4，,用于批量获取直播间的人数
			foreach ($ad_list as $key => $val) {
				$info = array();
				if($val['ad_type'] == 2){
					if($mi_uid > 0){
						$ad_list[$key]['focus_state'] = $this->users->get_user_focus_state($mi_uid, $val['top_id']);
					}else{
						$ad_list[$key]['focus_state'] = 2;
					}
					if(!in_array($val['top_id'], $uids)){
						$uids[] = $val['top_id'];
					}
				}elseif($val['ad_type'] == 3){
					if(!in_array($val['top_id'], $video_ids)){
						$video_ids[] = $val['top_id'];
					}
					if(isset($val['uid'])&&!empty($val['uid'])&&!in_array($val['uid'], $video_user_ids)){
						$video_user_ids[] = $val['uid'];
					}
				}elseif($val['ad_type'] == 4){
					if(!in_array($val['top_id'], $live_uids)){
						$live_uids[] = $val['top_id'];
					}
				}
			}
			

			//ad_type=2的获取用户粉丝数
			if(count($uids) > 0){
				$result = $this->users->get_user_fields($uids, "id AS uid, f_count, v_count, verified_anchor");
				$user_array = array();
				foreach ($result as $k => $v) {
					$user_array[$v['uid']] = $v;
				}
				foreach ($ad_list as $k1 => $v1) {
					if($v1['ad_type'] == 2){
						if(isset($user_array[$v1['top_id']])){
							$ad_list[$k1] = array_merge($ad_list[$k1], $user_array[$v1['top_id']]);
						}else{
							unset($ad_list[$k1]);
						}
					}
				}
			}

			//ad_type=3的获取视频播放量
			if(count($video_ids) > 0){
				
				$userinfolist=array();
				if(count($video_user_ids)>0){
					$userinfoarr = $this->users->get_user_fields($video_user_ids, "id AS uid,province, city");
				}
				if(isset($userinfoarr) && is_array($userinfoarr)){
					foreach ($userinfoarr as $uk=>$uv){
						$userinfolist[$uv['uid']] = $uv;
					}
				}
				
				$this->load->model('videos');
				$result = $this->videos->get_ad_video_info($video_ids);

				$video_array = array();
				foreach ($result as $k => $v) {
					$video_array[$v['vid']] = $v;
				}

				foreach ($ad_list as $k1 => $v1) {
					if($v1['ad_type'] == 3){
						if(isset($video_array[$v1['top_id']])){
							$ad_list[$k1] = array_merge($ad_list[$k1], $video_array[$v1['top_id']]);
							$ad_list[$k1] = array_merge($ad_list[$k1], $userinfolist[$v1['uid']]);
						}else{
							unset($ad_list[$k1]);
						}
					}
				}
			}

			//ad_type=4的获取房间人数
			if(count($live_uids) > 0){
				$result = $this->users->get_live_list($where = array('uid' => implode(",",$live_uids),'is_live'=>1,'is_push'=>1),0,1000);
				if(!empty($result)) {
					$result = $this->users->return_live_list($result);
				}
				
				$user_array = array();
				foreach ($result as $k => $v) {
					$v['history_count'] = $v['history_count'] + $v['h_count_base'];
					$v['h_count'] = $v['h_count'] + $v['h_count_base'];
					$user_array[$v['uid']] = $v;
				}

				foreach ($ad_list as $k1 => $v1) {
					if($v1['ad_type'] == 4){
						if(isset($user_array[$v1['top_id']])) {
							$user_level_info=$this->users->get_user_level_info($v1['uid']);
							$ad_list[$k1]['user_level_name']=$user_level_info['user_level_name'];
							$ad_list[$k1] = array_merge($ad_list[$k1], $user_array[$v1['top_id']]);
						}else {
							unset($ad_list[$k1]);
						}
					}
				}
			}
			return array_values($ad_list);
		}
		
    }